<template>
  <div>
    <el-card>
		<bread></bread>
      <el-row>
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="query">
            <el-button slot="append" icon="el-icon-search" @click="getuserlist"></el-button>
          </el-input>
        </el-col>
        <el-col :span="16">
          <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-table :data="userlist" style="width: 100%">
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column prop="role_name" label="角色"></el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
         
          <el-button type="primary" @click="editmyUser(scope.row)" icon="el-icon-edit" size="mini"></el-button>
       
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.$index, scope.row)"
            size="mini"
          ></el-button>

           <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start">
          <el-button type="warning" icon="el-icon-setting" size="mini"
          @click="setRole(scope.row)"></el-button>
           </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <el-dialog title="添加用户" :visible.sync="dialogFormVisible" @close="closeadd">
      <el-form :model="form" :rules="rules" ref="addFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑用户" :visible.sync="editDialogVisible">
      <el-form :model="editForm" :rules="editrules" ref="editFormRef">
        <el-form-item label="用户名" 上>
          <el-input v-model="editForm.username" disabled autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible">
      <div>
        <p>当前用户:{{userinfo.username}}</p>
        <p>当前角色:{{userinfo.role_name}}</p>
        <p>分配新角色
          <el-select v-model="selectRoleId" placeholder="请选择">
    <el-option
      v-for="item in rolelist"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
        </p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import userApi from "@/api/users.js"
import bread from "@/components/bread";
export default {
  components: {
    bread
  },
  data() {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[3|4|5|7|8][0-9]{9}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };

    return {
      userlist: [],
      selectRoleId:"", 
      userinfo:{}, 
      rolelist:[],
      pagenum: 1,
	  pagesize:2,
      query: "", 
      total: 0, 
      dialogFormVisible: false, 
      editDialogVisible: false, 
      setRoleDialogVisible:false, 
      form: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      editForm: {
        username: "",
        email: "",
        mobile: "",
      },
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          { validator: checkEmail, message: "邮箱格式不正确", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          {
            validator: checkMobile,
            message: "手机号格式不正确",
            trigger: "blur",
          },
        ],
      },
      editrules: {
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          { validator: checkEmail, message: "邮箱格式不正确", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          {
            validator: checkMobile,
            message: "手机号格式不正确",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getuserlist();
  },
  methods: {
    handleSizeChange(val) {
      this.pagesize = val;
	  this.getuserlist();
    },
    handleCurrentChange(val) {
      this.pagenum = val; 
      this.getuserlist(); 
    },
    setRole(userinfo){
     this.userinfo=userinfo
     userApi.getRole()
     .then(res=>{
        if(res.meta.status!=200){
          return this.$message.error("获取角色列表失败")
        }
       this.rolelist=res.data
     })
     this.setRoleDialogVisible=true
    },
    saveRole(){ //点击分配角色对话框中的确定按钮
     if(!this.selectRoleId){
       return this.$message.error("请选择您要分配的角色")
     }
    userApi.roles(this.userinfo.id,this.selectRoleId)
    .then(res=>{
      if(res.meta.status!=200){
         return this.$message.error("分配角色失败")
      }
       this.$message.success("分配角色成功")
       this.getuserlist()
       this.setRoleDialogVisible=false
    })
    },
    userStateChange(row) {
      userApi.changes(row.id,row.mg_state)
	  .then((res) => {
        if (res.meta.status == 200) {
          this.$message({
            showClose: true,
            message: "状态更新成功",
            type: "success",
          });
        } else {
          row.mg_state = !row.mg_state;
          this.$message({
            showClose: true,
            message: "状态更新失败",
            type: "error",
          });
        }
      });
    },
    closeadd() {
      this.$refs.addFormRef.resetFields();
    },
    editmyUser(row) {
      this.editDialogVisible = true; //弹框显示
      this.editForm = JSON.parse(JSON.stringify(row));
    },
    editUser() {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) {
          return;
        } else {
          console.log(this.editForm, "this");
          userApi.redact(this.editForm.id, {
              email: this.editForm.email,
              mobile: this.editForm.mobile,
            })
            .then((res) => {
              this.$message({
                showClose: true,
                message: "用户更新成功",
                type: "success",
              });
              this.getuserlist();
              this.editDialogVisible = false;
            });
        }
      });
    },
    addUser() {
      this.$refs.addFormRef.validate((valid) => {
        console.log(valid);
        if (!valid) {
          return;
        } else {
          userApi.addUsera(this.form)
		  .then((res) => {
            if (res.meta.status == 201) {
              this.$message({
                showClose: true,
                message: "添加成功",
                type: "success",
              });
              this.dialogFormVisible = false;
              this.getuserlist();
            }
          });
        }
      });
    },
    getuserlist() {
		userApi.getUser({
          params: {
            pagenum: this.pagenum, 
            pagesize: this.pagesize, 
            query: this.query,
          },
        })
        .then((res) => {
			console.log(res)
          if (res.meta.status == 200) {
            this.total = res.data.total;
            this.userlist = res.data.users;
          }
        });
    },
    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          userApi.remove(row.id).then((res) => {
            if (res.meta.status == 200) {
              this.getuserlist(); 
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>
<style lang="scss" scoped>
</style>